<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :search.sync="query"
      v-model="form"
      ref="crud"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val)"></user-table-config>-->
      <!--      </template>-->
      <template slot="status" slot-scope="{ row }">
        <el-tag effect="dark" type="danger" v-if="row.status === 0">禁用</el-tag>
        <el-tag effect="dark" type="success" v-else>启用</el-tag>
      </template>
      <template slot="menuLeft">
        <el-button type="warning" size="small" icon="el-icon-upload2" v-if="permission.noMachineStickersFeeding_import" @click="handleImport">导 入</el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" v-if="permission.noMachineStickersFeeding_delete" @click="handleDelete">删 除</el-button>
      </template>
      <template slot="menu" slot-scope="scope">
        <el-button type="text" size="small" icon="el-icon-view" @click="handleDetail(scope.row, scope.index)"> 详情 </el-button>
        <el-button type="text" size="small" icon="el-icon-edit" v-if="permission.noMachineStickersFeeding_edit" @click="handleEdit(scope.row, scope.index)"> 编辑 </el-button>
        <el-button type="text" size="small" icon="el-icon-delete" v-if="permission.noMachineStickersFeeding_delete" @click="handleRowDel(scope.row, scope.index)">
          删除
        </el-button>
        <el-button
          type="text"
          size="small"
          icon="el-icon-success"
          v-if="permission.noMachineStickersFeeding_enable && scope.row.status == 0"
          @click="handleRowEnable(scope.row)"
        >
          启用
        </el-button>
        <el-button
          type="text"
          size="small"
          icon="el-icon-remove"
          v-if="permission.noMachineStickersFeeding_disabled && scope.row.status == 1"
          @click="handleRowDisabled(scope.row)"
        >
          禁用
        </el-button>
      </template>
    </avue-crud>
    <el-dialog class="showDialog" ref="dialog" :title="dialogTitle" width="60%" append-to-body :visible.sync="showDialog" @close="closeDialog">
      <div class="sail-header-dialog-content">
        <avue-form v-if="showDialog" ref="form" v-model="form" :option="basicDataOption">
          <template #feedingDetail="{}">
            <avue-crud
              ref="editCrud"
              :option="feedingInfoOption"
              :data="feedingInfoList"
              @row-save="handleEditSave"
              @row-update="handleEditUpdate"
              @row-del="handleRowDelete"
              @selection-change="basicInfoSelectionChange"
            >
              <template slot-scope="{ row, index }" slot="partNoForm">
                <span v-if="!row.$cellEdit">{{ row.partNo }}</span>
                <el-input v-else placeholder="请选择物料编码" v-model="row.partNo" readonly
                  ><el-button slot="append" icon="el-icon-search" @click="openPartCommonModal(index)"></el-button
                ></el-input>
              </template>
              <template slot="menuLeft" v-if="dialogTitle === '编辑'">
                <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAddDetail">新 增</el-button>
                <el-button type="danger" size="small" icon="el-icon-delete" @click="handleDeleteDetail">删 除</el-button>
              </template>
            </avue-crud>
          </template>
          <template #changeLogTable="{}">
            <avue-crud :option="changeLogOption" :data="changeLogData">
              <template slot="menu" slot-scope="{ row, index }">
                <el-button
                  v-if="index == changeLogData.length - 1"
                  type="text"
                  size="small"
                  :disabled="form.tableVersion == row.tableVersion"
                  icon="el-icon-view"
                  @click="handleDetailRowView(row)"
                  >当前版本</el-button
                >
                <el-button v-else type="text" :disabled="form.tableVersion == row.tableVersion" size="small" icon="el-icon-view" @click="handleDetailRowView(row)"
                  >查看</el-button
                >
              </template>
            </avue-crud>
          </template>
        </avue-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="showDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
        <el-button v-if="dialogTitle === '编辑'" type="primary" size="small" @click="submit"><i class="el-icon-circle-plus-outline"></i><span>保 存</span> </el-button>
      </span>
    </el-dialog>
    <el-dialog title="非机贴上料表导入" append-to-body :visible.sync="importDialog" width="555px" @close="closeImportDialog">
      <avue-form ref="importForm" v-if="importDialog" :option="importOption" v-model="importForm" @submit="handleImportSubmit">
        <template slot="excelFile">
          <el-upload
            ref="excelFile"
            class="importConfigDialog"
            drag
            action="#"
            accept=".xlsx,.xls"
            :multiple="true"
            :auto-upload="false"
            :before-remove="handleBeforeRemove"
            :on-change="uploadBefore"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">
              <div>请上传 .xlsx,.xls标准格式文件</div>
            </div>
          </el-upload>
        </template>
      </avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" icon="el-icon-check" v-preventReClick @click="handleSubmit">保存</el-button>
        <el-button size="small" icon="el-icon-delete" @click="importDialog = false">取消</el-button>
      </span>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :key="timer" :option="tableOption" @getSelectedRows="getSelectedRows" @newKey="newKey"></common-modal-template>
  </basic-container>
</template>

<script>
import { getList, getDetail, getLog, update, remove, enable, disable, importCheck, importSubmit } from '@/api/product/noMachineStickersFeeding';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
export default {
  name: 'ProductNoMachineStickersFeeding',
  components: {
    CommonModalTemplate,
    userTableConfig,
    userConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      option: {
        height: 'calc(100vh - 480px)',
        rowKey: 'id',
        rowParentKey: 'parentId',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        border: true,
        index: false,
        indexLabel: '序号',
        searchMenuSpan: 24,
        searchLabelWidth: 90,
        viewBtn: false,
        editBtn: false,
        addBtn: false,
        delBtn: false,
        columnBtn: false,
        labelWidth: 130,
        selection: true,
        highlightCurrentRow: true, // 选中高亮
        dialogClickModal: false,
        searchMenuPosition: 'right',
        menuWidth: 300,
        column: [
          {
            label: '上料表名称',
            prop: 'name',
            search: true
          },
          {
            label: '机型',
            prop: 'partModel',
            search: true
          },
          {
            label: '版本',
            prop: 'tableVersion',
            search: true
          },
          {
            label: '状态',
            prop: 'status',
            search: true,
            type: 'select',
            dicData: [
              {
                label: '启用',
                value: 1
              },
              {
                label: '禁用',
                value: 0
              }
            ]
          },
          {
            label: '上料表编码',
            prop: 'code'
          }
        ]
      },
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      data: [],
      showDialog: false,
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      dialogTitle: '编辑',
      basicDataOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 150,
        detail: false,
        group: [
          {
            label: '基础信息',
            prop: 'basicInfo',
            arrow: false,
            icon: 'el-icon-vertical-bar',
            display: true,
            column: [
              {
                label: '上料表名称',
                prop: 'name',
                rules: [
                  {
                    required: true,
                    message: '请选择上料表名称',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '机型',
                prop: 'partModel',
                rules: [
                  {
                    required: true,
                    message: '请选择机型',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '版本',
                prop: 'tableVersion',
                rules: [
                  {
                    required: true,
                    message: '请输入版本',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '上料表编码',
                prop: 'code',
                disabled: true
              }
            ]
          },
          {
            label: '上料表详情',
            prop: 'feedingDetail',
            arrow: false,
            icon: 'el-icon-vertical-bar',
            column: [
              {
                label: '',
                prop: 'feedingDetail',
                labelWidth: 0,
                span: 24
              },
              {
                label: '修改原因',
                prop: 'remark',
                labelPosition: 'top',
                span: 24,
                type: 'textarea',
                minRows: 3,
                maxlength: 100,
                showWordLimit: true,
                display: true,
                rules: [
                  {
                    required: true,
                    message: '请输入修改原因',
                    trigger: 'blur'
                  }
                ]
              }
            ]
          },
          {
            label: '修改日志',
            prop: 'changeLog',
            arrow: false,
            icon: 'el-icon-vertical-bar',
            display: false,
            column: [
              {
                label: '',
                prop: 'changeLogTable',
                labelWidth: 0,
                span: 24
              }
            ]
          }
        ]
      },
      feedingInfoOption: {
        height: 300,
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        viewBtn: false,
        selection: true,
        dialogClickModal: false,
        refreshBtn: false,
        columnBtn: false,
        cellBtn: true,
        menu: true,
        column: [
          {
            label: '工段',
            prop: 'sectionName',
            cell: true
          },
          {
            label: '物料编码',
            prop: 'partNo',
            cell: true,
            rules: [
              {
                required: true,
                message: '请选择物料编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '物料规格',
            prop: 'partModel'
          },
          {
            label: '用量',
            prop: 'quantity',
            cell: true,
            type: 'number',
            precision: 0,
            minRows: 1,
            rules: [
              {
                required: true,
                message: '请输入用量',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      feedingInfoList: [],
      editRowIndex: '',
      basicInfoSelectionList: [],
      changeLogOption: {
        height: 300,
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        editBtn: false,
        viewBtn: false,
        delBtn: false,
        selection: false,
        dialogClickModal: false,
        refreshBtn: false,
        columnBtn: false,
        column: [
          {
            label: '编辑人',
            prop: 'updateUserName'
          },
          {
            label: '修改时间',
            prop: 'updateTime'
          },
          {
            label: '修改原因',
            prop: 'remark'
          }
        ]
      },
      changeLogData: [],
      importDialog: false,
      importForm: {
        file: []
      },
      importOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 100,
        column: [
          {
            label: '附件上传',
            prop: 'excelFile',
            span: 24
          }
        ]
      }
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  computed: {
    ...mapGetters(['permission']),
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  methods: {
    handleRowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDetail(row, index) {
      this.dialogTitle = '详情';
      this.showDialog = true;
      this.basicDataOption.detail = true;
      this.feedingInfoOption.menu = false;
      this.basicDataOption.group[2].display = true;
      let remark = this.findObject(this.basicDataOption.group[1].column, 'remark');
      remark.display = false;
      this.form = row;
      getDetail({ tableId: row.id, current: 1, size: 1000 }).then(
        (res) => {
          this.feedingInfoList = this._get(res, 'data.data.records', []);
        },
        (error) => {
          this.feedingInfoList = [];
        }
      );
      getLog(row.id).then(
        (res) => {
          this.changeLogData = this._get(res, 'data.data', []);
        },
        (error) => {
          this.changeLogData = [];
        }
      );
    },
    handleEdit(row, index) {
      this.dialogTitle = '编辑';
      this.showDialog = true;
      this.basicDataOption.detail = false;
      this.feedingInfoOption.menu = true;
      this.basicDataOption.group[2].display = false;
      let remark = this.findObject(this.basicDataOption.group[1].column, 'remark');
      remark.display = true;
      this.form = row;
      this.form.remark = '';
      getDetail({ tableId: row.id, current: 1, size: 1000 }).then(
        (res) => {
          this.feedingInfoList = this._get(res, 'data.data.records', []);
        },
        (error) => {
          this.feedingInfoList = [];
        }
      );
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('是否确认删除勾选产品的全部产能信息？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      let len = list.length - 1;
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    onLoad(page, params = {}) {
      this.loading = true;
      params.tableType = 'NON_MACHINE_STICKER';
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    newKey() {
      this.timer = new Date().getTime();
    },
    handleAddDetail() {
      this.feedingInfoList.push({
        $cellEdit: false,
        sectionName: '',
        partNo: '',
        partModel: '',
        quantity: undefined
      });
    },
    openPartCommonModal(index) {
      this.editRowIndex = index;
      this.modalName = 'partModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择产品（双击进行选择）',
        url: '/api/mes-admin/part-master/page?semifinished=false',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '物料编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '物料名称',
            prop: 'name',
            search: true
          },
          {
            label: '物料分类',
            prop: 'categoryName'
          },
          {
            label: '物料型号',
            prop: 'partModel'
          }
        ]
      };
    },
    /**
     * 双击模态框行
     */
    getSelectedRows(row) {
      switch (this.modalName) {
        case 'partModal':
          let obj = this._find(this.feedingInfoList, { partNo: row.partNo });
          if (!obj) {
            this.feedingInfoList[this.editRowIndex].partNo = row.partNo;
            this.feedingInfoList[this.editRowIndex].partModel = row.partModel;
          }
          break;
        default:
          break;
      }
    },
    basicInfoSelectionChange(list) {
      this.basicInfoSelectionList = list;
    },
    handleDeleteDetail() {
      if (this.basicInfoSelectionList.length === 0) {
        this.$message.warning('请至少勾选一条数据');
        return;
      }
      this._forEach(this.basicInfoSelectionList, (item) => {
        let index = this._findIndex(this.feedingInfoList, { partNo: item.partNo });
        this.feedingInfoList.splice(index, 1);
      });
    },
    handleEditSave(row, done) {
      done();
    },
    handleEditUpdate(row, index, done) {
      done();
    },
    handleRowDelete(row, index) {
      this.feedingInfoList.splice(index, 1);
    },
    handleDetailRowView(row) {
      this.form = row;
      getDetail({ tableId: row.id, current: 1, size: 1000 }).then(
        (res) => {
          this.feedingInfoList = this._get(res, 'data.data.records', []);
        },
        (error) => {
          this.feedingInfoList = [];
        }
      );
    },
    submit() {
      this.$refs.form.validate((valid, done) => {
        if (valid) {
          if (this.feedingInfoList.length > 0) {
            for (let i = 0; i < this.feedingInfoList.length; i++) {
              if (!this.feedingInfoList[i].partNo) {
                this.$message.warning('上料表详情中物料编码不能为空！');
                return;
              }
              if (!this.feedingInfoList[i].quantity) {
                this.$message.warning('上料表详情中用量不能为空！');
                return;
              }
            }
          }
          let params = {
            smtTable: this.form,
            smtTrackDTO: this.feedingInfoList
          };
          update(params).then((res) => {
            this.showDialog = false;
            this.$message.success(res.data.msg);
            this.onLoad(this.page);
            done();
          });
        }
      });
    },
    handleRowEnable(row) {
      this.$confirm('是否确定启用这条数据?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        enable(row.id).then((res) => {
          this.$message.success(res.data.msg);
          this.onLoad(this.page);
        });
      });
    },
    handleRowDisabled(row) {
      this.$confirm('是否确定禁用这条数据?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        disable(row.id).then((res) => {
          this.$message.success(res.data.msg);
          this.onLoad(this.page);
        });
      });
    },
    handleImport() {
      this.importDialog = true;
    },
    closeImportDialog() {
      this.$refs.importForm.resetFields();
      this.importForm = {
        file: []
      };
    },
    uploadBefore(file) {
      let nameArray = file.name.split('.');
      if (nameArray[nameArray.length - 1] === 'xlsx' || nameArray[nameArray.length - 1] === 'xls') {
        // file保存选择的文件
        this.importForm.file.push(file.raw);
        console.log(this.importForm);
      } else {
        this.$message({
          message: `${file.name}文件格式错误,请确认文件内容并重新上传`,
          type: 'warning',
          duration: 2000
        });
      }
    },
    async handleBeforeRemove(file, fileList) {
      let res = await this.$confirm(`确定移除 ${file.name}？`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      });
      if (res) {
        this.importForm.file = this.importForm.file.filter((item) => item.uid !== file.uid);
        this.$message({
          type: 'success',
          message: '移除成功!'
        });
      }
    },
    handleSubmit() {
      this.$refs.importForm.submit();
    },
    handleImportSubmit(form, done) {
      if (this.importForm.file.length === 0) {
        this.$message.warning('请上传附件！');
        return;
      }
      let formData = new FormData();
      this.importForm.file.forEach((item) => {
        formData.append('file', item);
      });
      importCheck(formData).then(
        (res) => {
          let checkRes = res.data;
          const repeatArr = checkRes.data.filter((i) => !i.success).map((i) => i.fileName);
          if (checkRes && repeatArr.length > 0) {
            const repeatArr = checkRes.data.filter((i) => !i.success).map((i) => i.fileName);

            this.$confirm(`<p class='confirm-message-wrap'>${repeatArr.join(',')}重复,是否覆盖?</p>`, {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              dangerouslyUseHTMLString: true,
              type: 'warning'
            })
              .then(async () => {
                this.importData();
                done();
              })
              .catch(() => {
                const file = this.importForm.file.filter((item) => {
                  return !repeatArr.includes(item.name);
                });
                this.importForm.file = file;
                if (!this.importForm.file.length) {
                  return;
                }
                this.importData();
                done();
              });
          } else {
            this.importData();
            done();
          }
        },
        (error) => {
          done();
        }
      );
    },
    importData() {
      let formData = new FormData();
      this.importForm.file.forEach((item) => {
        formData.append('file', item);
      });
      importSubmit(formData).then(
        (res) => {
          this.$message.success('导入成功');
          this.importDialog = false;
          this.$refs.importForm.resetFields();
          this.onLoad(this.page);
        },
        (error) => {}
      );
    },
    closeDialog() {
      this.$refs.form.resetFields();
      this.form = {};
      this.feedingInfoList = [];
      this.changeLogData = [];
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-table__header {
  thead {
    th {
      background-color: #fafafa;
      padding: 8px 0;
      color: rgba(0, 0, 0, 0.85);
      font-size: 12px;
    }
  }
}
.showDialog {
  .el-table__body td {
    .el-button {
      padding: 9px 15px;
    }
  }
}
</style>
